import { defineStore } from 'pinia'
import { Project } from '@/types/system/device-maintenance/project'
import {
  getProjectsAsync,
  insertProjectAsync,
  deleteProjectAsync
} from '@/api/axios/device-maintenance-client'
export const useDeviceMaintenanceProjectStore = defineStore('device-maintenance-project', {
  state: () => {
    return {
      // 是否加载项目
      isNeedLoadProjects: true,
      // 项目列表
      projects: [] as Project[]
    }
  },
  actions: {
    // 更新项目列表
    async updateProjectsAsync() {
      const result = await getProjectsAsync(0, 100)
      if (result.isSuccess) {
        this.projects = result.result ?? []
        this.isNeedLoadProjects = false
      }
      return result.isSuccess
    },
    // 插入一个项目
    async insertProjectAsync(newProject: Project) {
      const result = await insertProjectAsync(newProject)
      if (result.isSuccess) {
        await this.updateProjectsAsync()
      }
      return result.isSuccess
    },
    // 删除一个项目
    async deleteProjectAsync(id: string) {
      const result = await deleteProjectAsync(id)
      if (result.isSuccess) {
        await this.updateProjectsAsync()
      }
      return result.isSuccess
    }
  },
  getters: {
    projectNames(): string[] {
      return this.projects.map((item) => item.projectName)
    }
  }
})
